<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/classes/Template.class.php, $Author:  $ */

/**
 *  Smarty template object extension
 * @package core
 */
class Template extends Smarty
{
    /** Template file name (_template.html by default)
     * @var string
     */
    var $sTemplateFile = '_template.html';

    /** Constructor
     */
    function Template($aConf=array())
    {
        if (!$aConf)
        {
            $aConf = App::getParam('template');
         }

        $this->template_dir  = $aConf['dir'] . "/". App::getLayout() ."";
        $this->compile_dir   = $aConf['c_dir'];
		$this->cache_dir = $aConf['p_dir'];
        $this->force_compile = false;
        // $this->use_sub_dirs = true;

        if ( !compile_check )
        {
        	$this->compile_check = false;
        }

        $oLang = &App::getLanguage();

        parent::assign(array
        (
        	'sBaseUrl' => $aConf['url'],
        	'sBaseDir' => App::getParam('path'),
        	'phpfoxCache' => phpfoxCache,
        	'getPage' => str_replace("public.", '', App::getPage()),
        	'aGlobalLang' => $oLang->getDetails(),
        	'sSmartyTemplateDir' => $this->template_dir
        ));
    }

    /** Set template file name (overwrite default "_template.html")
     *
     * @param string $sFile  template file name
     */
    function setTemplateFile($sFile)
    {
        $this->sTemplateFile = $sFile;
    }

    /** Fetch template. Performs addMess() and call parent fetch() method
     *
     * @see Smarty::fetch()
     * @param string $resource_name
     * @param string $cache_id
     * @param string $compile_id
     * @param bool   $display
     * @return string
     */
    function fetch($resource_name, $cache_id = null, $compile_id = null, $display = false)
    {
    	if ( defined("benchMark") AND benchMark AND App::getParam('debug') )
    	{
    		$checkRequire = new BenchMark;
			$checkRequire->start();
		}

		static $sStyleFile, $sStyleDir, $sStyleName;

		if ( !$sStyleFile AND !$sStyleDir )
		{
        	$oStyleService = &App::getModuleService('Site', 'Style');
        	/* @var $oStyleService PhpFox_Mod_Site_ServiceStyle */
        	$oReq =& App::getRequest();
        	if (App::getParam('protheme') && ($sName = $oReq->get('name')))
        	{
        		$oDb =& Database::get();
        		$aRow = $oDb->getRow("
        			SELECT p.file
        			FROM ". App::getT('user') ." AS u
        				LEFT JOIN ". App::getT('css') ." AS p ON(u.plugin_style = p.id)
        			WHERE u.user = '". $oDb->escape($sName) ."'"
        		);
        		if (isset($aRow['file']))
        		{
        			$sStyleFile = $aRow['file'];
        			$sStyleName = $aRow['file'];
        			$sStyleDir = 'default';
        		}
         	}

         	if (empty($sStyleFile))
         	{
				list($sStyleFile, $sStyleName, $sStyleDir) = $oStyleService->getUserStyle();
         	}
		}

       parent::assign(array(
        	'sDateTimeFormat'  => App::getParam('format.datetime%'),
        	'sDateFormat'      => App::getParam('format.date%'),
        	'sDateFormatShort' => App::getParam('format.dateshort%'),
            'sDateFormatDot'   => App::getParam('format.monthdatedot'),
            'sTimeFormat'      => App::getParam('format.time%'),
            'sStylePath'       => 'file/style/'.$sStyleFile.'/',
            'bRemoveBrand'     => App::removeBrand(),
            'sPhpFoxVersion'   => App::getParam('info.version'),
            'sStyleDir'       => isset($sStyleDir) ? $sStyleDir : '',
            'bUseAjax' => App::getParam('useAjax'),
            'bIsAdmins' => App::isStaff(),
        ));

       $compile_id = md5(App::getParam('info.version') . App::getParam('info.build') . $this->template_dir);

        App::setParam('tpl_processing', 1);
        $srcRes = parent::fetch($resource_name, $cache_id, $compile_id, $display);
        App::setParam('tpl_processing', 0);

        if ( defined("benchMark") AND benchMark AND App::getParam('debug') )
        {
        	global $debugTemplate;
        	$debugTemplate[] = array
        	(
        		'name' => $this->template_dir . $resource_name,
        		'time' =>$checkRequire->finish2(),
        	);
        }

		$sTemplateInfo = "";
		$sTemplateInfo .= (App::getParam('show_templates_name') ? '<!-- ### Start phpFoX Template: '. $resource_name .' ### -->' . "\n" : '');
		$sTemplateInfo .= $srcRes;
		$sTemplateInfo .= (App::getParam('show_templates_name') ? '<!-- ### End phpFoX Template: '. $resource_name .' ### -->' . "\n" : '');

        return $sTemplateInfo;
    }

    /** Display
     * @see Smarty::display()
     */
    function view($sTpl, $sDir='', $user_theme_id = '')
    {
        $this->assign(array(
            'sTplName'   => $sTpl,
            'sTplPanel' => (file_exists($this->template_dir . "/" .str_replace("public","sidepanel",$sTpl)) ? str_replace("public","sidepanel",$sTpl) : ''),
        ));

        if (!$sDir)
        {
            $sDir = substr($sTpl, 0, strpos($sTpl, '/'));
        }

        //special processing for _template.html -- search up in folders
        if ('_template.html'  == $this->sTemplateFile)
        {
            $sOldDir = $sDir;
            $sFullPath = $this->template_dir.'/'.$sDir.'/'.$this->sTemplateFile;
            while (!file_exists($sFullPath) && ($sDir!=''))
            {
                $aPath = explode('/', $sDir);
                array_pop($aPath);
                $sDir = implode('/', $aPath);
                $sFullPath = $this->template_dir.'/'.$sDir.'/'.$this->sTemplateFile;
            }

            if ('' == $sDir)
            {
                $sDir = $sOldDir; //restore old path
            }
        }

        //separate fetch and display -- to solve problem with block processing
        // (cannot redirect problem)
        $sHtml = $this->fetch($sDir.'/'.$this->sTemplateFile);
        print $sHtml;
    }

    /** Add message
     *
     * @param string $sUrl
     */
    function addMes($sUrl='')
    {
		return;
    }

    /** Assign value with html escaping
     *
     * @param array|string $tpl_var the template variable name(s)
     * @param mixed $value the value to assign
     */
    function assign($mVar, $mVal=null)
    {
        if (is_array($mVar))
        {
            foreach($mVar as $sVal=>$mVal)
                parent::assign($sVal, $mVal);
        }
        elseif(! is_object($mVar))
        {
            parent::assign($mVar, $this->_escape($mVal));
        }
    }

    /** Assign value without escaping
     *
     * @param array|string $tpl_var the template variable name(s)
     * @param mixed $value the value to assign
     */
    function assignSrc($mVar, $mVal=null)
    {
        parent::assign($mVar, $mVal);
    }

    /** Performs html escaping (for complex type too)
     *
     * @todo do something with class!!!
     *
     * @param mixed $mVal
     * @return mixed
     */
    function _escape($mVal)
    {
        if (is_array($mVal))
        {
            foreach($mVal as $k=>$v)
                $mVal[$k] = $this->_escape($v);
        }
        elseif(is_object($mVal))
        {
            /** @todo do something with class!!! */
        }
        else
            $mVal = htmlspecialchars($mVal);

        return $mVal;
    }
}
?>